package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.TrackListAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.TrackBean;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.TipDialog;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.TrackPop;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.CommonAdapter;
import butterknife.Bind;
import butterknife.OnClick;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by yidong on 2017/8/29.
 */

public class OrderHighSeas extends BaseActivity implements SpringView.OnFreshListener, TrackListAdapter.OrderListener, TipDialog.CallBack, CommonAdapter.OnItemClickListener {
    @Bind(R.id.tv_title)
    TextView titleTV;
    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.spring_view)
    SpringView springView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.tv_car_name_title)
    TextView nameTv;
    @Bind(R.id.title_view)
    View titleView;
    @Bind(R.id.edit_search_name)
    EditText searchEdit;

    private TipDialog tipDialog;
    private String dispatch_ID;
    private Intent mIntent;
    private List<TrackBean> trackList = new ArrayList<TrackBean>();
    private int page = 1;
    private int type = 1;
    private String keyWord;
    private TrackListAdapter adapter;
    private TrackPop trackPop;
    private boolean isLodmore = true;
    private boolean isShowDialog = true;

    @Override
    protected int getLayout() {
        return R.layout.activity_track_list;
    }

    @Override
    protected void initEventAndData() {
        mIntent = new Intent();
        titleTV.setText("订单公海");
        returnLin.setVisibility(View.VISIBLE);
        springView.setListener(this);
        springView.setHeader(new DefaultHeader(this));
        springView.setFooter(new DefaultFooter(this));
        springView.setType(SpringView.Type.FOLLOW);
        springView.setType(SpringView.Type.FOLLOW);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        getIntentFuzzyQueryA();
    }

    @Override
    protected void createPresenter() {
        getHighSeasList(this, page, type, keyWord);
    }

    @Override
    public void onRefresh() {
        isShowDialog = false;
        page = 1;
        getHighSeasList(this, page, type, keyWord);
    }

    @Override
    public void onLoadmore() {
        isShowDialog = false;
        if (isLodmore) {
            page++;
            getHighSeasList(this, page, type, keyWord);
        }else {
            springView.onFinishFreshAndLoad();
        }

    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
//        CustomSharedPreferences.saveString(OrderHighSeas.this, new MapUtil().put(KeyBean.ORDER_ID.valueOf(), adapter.getDatas().get(position).getDispatch_id()).build(), KeyBean.FILE_NAME.valueOf());
//        mIntent.setClass(OrderHighSeas.this, CustomerDetailsActivity.class);
//        mIntent.putExtra("CREATE_ORDER", false);
//        startIntent(mIntent, false);
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    @Override
    public void acceptOrder(String dispatch_id) {
        dispatch_ID = dispatch_id;
        CustomSharedPreferences.saveString(this, new MapUtil().put(KeyBean.ORDER_ID.valueOf(), dispatch_id).build(), KeyBean.FILE_NAME.valueOf());
        if (tipDialog == null)
            tipDialog = new TipDialog(this, this);
        tipDialog.setMessageText("是否确定领取?");
        tipDialog.show();
    }

    @Override
    public void tipCallBack() {
        HashMap<String, Object> map = new MapUtil()
                .put("dispatch_id", dispatch_ID)
                .build();
        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(OrderHighSeas.this, map).create(IApiActivityRequest.class).receiveDispatch(),
                new BaseSubscriber<TokenBean>(OrderHighSeas.this) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        showToast(o.getMessage());
                        if (o.getStatus_code() == 0){
                            isShowDialog = false;
                            springView.callFresh();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        cancelLoading();
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        showLoading();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        cancelLoading();
                    }
                });

    }

    @OnClick({R.id.iv_return, R.id.tv_car_name_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                finish();
                break;
            case R.id.tv_car_name_title:
                trackPop = new TrackPop(this, popListener);
                trackPop.showAsDropDown(titleView, 40, 20);
                break;
        }
    }

    public void getHighSeasList(Context context, final int page, int type, String keyword) {
//        page 否 int 页码、分页参数，不传默认为1
//        size 否 int 每页最大请求数，默认为10
//        type 否 int 搜索类型：1，客户名；2，品牌、车系名；3，订单号
//        keyword 否 str 搜索关键字
        HashMap<String, Object> map = new MapUtil()
                .put("page", page)
                .put("type", type)
                .put("keyword", keyword)
                .build();

        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(context, map).create(IApiActivityRequest.class).getOrderSaesList(),
                new BaseSubscriber<TokenBean<List<TrackBean>>>(context) {
                    @Override
                    public void onSuccess(TokenBean<List<TrackBean>> o) {
                        if (o.getData() != null && o.getData().size() > 0) {
                            setDates(o.getData());
                            isLodmore = true;
                        } else {
                            showToast("没有数据！");
                            if (page == 1) {
                                adapter = null;
                                recyclerView.setAdapter(adapter);
                            }
                            isLodmore = false;
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        cancelLoading();
                        springView.onFinishFreshAndLoad();
                    }

                    @Override
                    public void onStart() {
                        if (isShowDialog)
                            showLoading();
                    }

                    @Override
                    public void onCompleted() {
                        cancelLoading();
                        springView.onFinishFreshAndLoad();
                    }
                });
    }

    private void setDates(List<TrackBean> datas) {
        if (page == 1) {
            trackList.clear();
        }
        trackList.addAll(datas);
        if (adapter == null) {
            adapter = new TrackListAdapter(this, R.layout.layout_item_order_cule, trackList);
            adapter.setBtnStr("领取");
            recyclerView.setAdapter(adapter);
            adapter.setListener(this);
            adapter.setOnItemClickListener(this);
        } else {
            adapter.refresh(trackList);
        }
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.tv_client_name:
                    nameTv.setText("客户名");
                    searchEdit.setHint("请输入客户名称");
                    type = 1;
                    page = 1;
                    break;
                case R.id.tv_car_name:
                    nameTv.setText("主车");
                    searchEdit.setHint("请输入品牌/车系");
                    type = 2;
                    page = 1;
                    break;
                case R.id.tv_order_id:
                    nameTv.setText("订单号");
                    type = 3;
                    page = 1;
                    searchEdit.setHint("请输入订单号");
                    break;

            }
            if (trackPop.isShowing()) {
                trackPop.dismiss();
            }
        }
    };

    public void getIntentFuzzyQueryA() {

        searchEdit.setOnKeyListener(new View.OnKeyListener() {//输入完后按键盘上的搜索建
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //判断是否按下。
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    //判断是否是回车键
                    if (keyCode == event.KEYCODE_ENTER) {
                        String keyWord = searchEdit.getText().toString();
                        //为NULL 判断
                        if (!TextUtils.isEmpty(keyWord)) {
                            getHighSeasList(OrderHighSeas.this, page, type, keyWord);
                        }
                    }

                }
                return false;
            }

        });
    }

}
